package com.emm.yixun.website.controller.marketing;
//框架包
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.emm.yixun.common.model.enums.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.emm.yixun.anotations.AvoidDuplicateSubmission;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.BusinessAbnorma;
//变化的引用
import com.emm.yixun.common.model.PriceScheme;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.TreeNode;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.PriceSchemeDto;
import com.emm.yixun.common.model.dto.PriceSchemeView;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.page.Page;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.estate.service.ProjectSettingServiceFacade;
import com.emm.yixun.estate.service.ProjectTreeServiceFacade;
import com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade;
import com.emm.yixun.marketing.service.PriceSchemeDetailServiceFacade;
import com.emm.yixun.marketing.service.PriceSchemeServiceFacade;
import com.emm.yixun.system.service.BusinessLogServiceFacade;
import com.emm.yixun.system.service.ImageServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.ActivitiProcessServiceImpl;
import com.emm.yixun.website.service.CacheUtils;
import com.emm.yixun.website.service.image.WsImageService;
import com.emm.yixun.website.service.marketing.PriceSchemeService;
import com.emm.yixun.website.utils.TokenProcessor;
@Controller
@RequestMapping("/marketing/priceScheme/")
public class PriceSchemeController extends BaseController<PriceScheme>{
	
	@Autowired
	private PriceSchemeServiceFacade priceSchemeServiceFacade;
	@Autowired
	private PriceSchemeService priceSchemeService;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	@Autowired
	private PriceSchemeDetailServiceFacade priceSchemeDetailServiceFacade;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private BusinessAbnormaServiceFacade businessAbnormaServiceFacade;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;
	@Autowired
	private ImageServiceFacade imageServiceFacade;
	@Autowired
	private WsImageService wsImageService;
	@Autowired
	private ProjectTreeServiceFacade projectTreeServiceFacade;
	@Autowired
	private BusinessLogServiceFacade businessLogServiceFacade;
	
	
	@RequestMapping(value="index")
	public String index(ModelMap map, HttpServletRequest request){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			map.put("permitBtn", getPermissionBtnArray());
			map.put("resourcesCode", request.getParameter("menu"));
			return "/marketing/priceScheme/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	@RequestMapping(value = "addView")
	@AvoidDuplicateSubmission(needSaveToken = true)
	public ModelAndView addView(HttpServletRequest request){
		String treeId = request.getParameter("treeId");
		Map<String, String> map =  strBuff(treeId);
		return new ModelAndView("/marketing/priceScheme/add")
		.addObject("treeId", request.getParameter("treeId"))
		.addObject("manageObject", map.get("manageObject"));
	}
	/**
	* 方法描述 : 方案房产
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： PriceSchemeController.java
	* 版本： v1.0
	* 创建时间： 2016年8月2日 上午9:44:21
	* @param treeId
	* @return AjaxRes
	 */
	@RequestMapping(value = "findProjectLink")
	public @ResponseBody AjaxRes findProjectLink(String treeId){
		AjaxRes ajaxRes = getAjaxRes();
		Map<String, String> map =  strBuff(treeId);
		ajaxRes.setSucceed(map.get("manageObject"));
		return ajaxRes;
	}
	
	public Map<String, String> strBuff(String str){
		Long bid = new Long(str.subSequence(str.indexOf("_")+1, str.length()).toString());
		String sub = str.subSequence(0, str.indexOf("_")).toString();
		LevelEnum level = LevelEnum.getByNo(sub);
		Map<String, String> resMap = new HashMap<String, String>();
		if(level.getName().equals("5")){
			Response<ProjectRoom> resResponse = projectRoomServiceFacade.findById(bid);
			
			if(resResponse.isSuccess()){
				resMap.put("manageObject", resResponse.getEntity().getCombinedName());
			}
			return resMap;
		}else{
			if(level.getName().equals("6")){
				 resMap.put("manageObject", priceSchemeServiceFacade.strByCarPort(bid, 1L));
				 return resMap;
			}else if(level.getName().equals("7")){
					resMap.put("manageObject", priceSchemeServiceFacade.strByCarPort(bid, 0L));
				 return resMap;
			}else{
				return projectServiceFacade.projectLevelName(bid, level.getName());
			}
			
		}
		
	}
	
	@RequestMapping(value = "schemeView")
	public ModelAndView schemeView(Long id,String processFlag){
		String treeId = priceSchemeServiceFacade.findTreeIdByBesId(id);
		Response<PriceScheme> priceScheme=priceSchemeServiceFacade.findWithOutDelById(id);
		if(!StringUtils.isEmpty(processFlag)){
			String priceSchemeStr = JSON.toJSONString(priceScheme.getEntity());
			com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSONObject.parseObject(priceSchemeStr);
			if(null!=priceScheme.getEntity().getExecutionDate())
			data.put("executionDate", DateUtils.DateToString(priceScheme.getEntity().getExecutionDate(), DateStyle.YYYY_MM_DD));
			else
				data.put("executionDate","");	
			return new ModelAndView("/marketing/priceScheme/priceSchemeView").addObject("priceSchemeId", id).addObject("priceScheme", data).addObject("processFlag", processFlag);
		}
		return new ModelAndView("/marketing/priceScheme/add")
		.addObject("treeId", treeId)
		.addObject("manageObject", priceScheme.getEntity().getSecheme())
		.addObject("id", id)
		.addObject("priceScheme", JSONObject.fromObject(priceScheme.getEntity()))
		.addObject("processFlag", processFlag);
	}
	//新增返回实体对象
	@RequestMapping(value="add")
	@ResponseBody
	@AvoidDuplicateSubmission(needRemoveToken = true)
    public AjaxRes  add(PriceSchemeDto dto,String gridJson,String execution,String fileUrlArr, String imageType, HttpServletRequest request){
    	AjaxRes ar=getAjaxRes();
    	//操作失败时,重新刷新提交Token
    	String newToken = TokenProcessor.getInstance().generateToken(request);
    	request.getSession(false).setAttribute("token", newToken);
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
    	User user = ShiroUtil.getCurrentUser();
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:priceScheme:add"))){
        	try {
        		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        		if(!StringUtils.isEmpty(execution)){
        			dto.setExecutionDate(df.parse(execution));
        		}
        		JSONArray jsonarray = JSONArray.fromObject(gridJson);
        		@SuppressWarnings("unchecked")
        		List<Object> objectList = (List<Object>) JSONArray.toCollection(jsonarray, Object.class);
        		List<PriceSchemeView> view = new ArrayList<PriceSchemeView>();
        		String roomId="";
        		for (int i = 0; i < objectList.size(); i++) {
        			JSONObject jsonObject=JSONObject.fromObject(objectList.get(i));
        			PriceSchemeView sc = (PriceSchemeView)JSONObject.toBean(jsonObject,PriceSchemeView.class);
        			roomId=sc.getId().split("_")[1];
        			view.add(sc);
				}
        		if(org.apache.commons.lang3.StringUtils.isBlank(roomId)){
        			ar.setFailMsg("价格方案未设置房间数据！");
        			ar.setObj(newToken);
        			return ar;
        		}
        		Response<ProjectRoom> resResponse = projectRoomServiceFacade.findById(Long.valueOf(roomId));
        		ProjectRoom projectRoom=resResponse.getEntity();
        		if(null == projectRoom) {
        			ar.setFailMsg("导入的房源不存在,请核对!");
        			ar.setObj(newToken);
        			return ar;
        		}
				Long projectId=projectRoom.getProjectId();
				if(null==projectId){
					ar.setFailMsg("项目不存在!");
					ar.setObj(newToken);
        			return ar;
				}
				//动态获取价格方案流程KEY
				String startProcessKey= activitiProcessService.getProcessKey(user.getMerchantId(),projectId,ProcessTypeEnums.PROCESS_KEY_1);
				if(StringUtils.isEmpty(startProcessKey)){
					ar.setFailMsg("未设置价格方案流程,请去项目流程菜单配置！");
					ar.setObj(newToken);
        			return ar;
				}
				//检查流程节点是否已设置人员
        		boolean isSeting=activitiProcessService.checkNodeUser(user.getMerchantId(),projectId,startProcessKey);
        		if(!isSeting){
        			ar.setFailMsg("价格方案审批流程节点人员未设置");
        			ar.setObj(newToken);
        			return ar;
        		}
				Response<PriceSchemeDto> response=priceSchemeServiceFacade.save(dto,view,ShiroUtil.getCurrentUser());
				if(response.isSuccess()){
					//启动审批流程
					
					identityService.setAuthenticatedUserId(user.getUserAccount());
					String pid=activitiProcessService.startProcessInstance(user.getMerchantId(),projectId, startProcessKey, response.getEntity().getId().toString(), null);
					//更新流程id到业务表
					PriceSchemeDto updateDto = new PriceSchemeDto();
					updateDto.setId(response.getEntity().getId());
					updateDto.setProcInstId(pid);
					priceSchemeServiceFacade.updateByPrimaryKey(updateDto, true);
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
					
					//保存流程附件(ym)
					if(org.apache.commons.lang3.StringUtils.isNotBlank(fileUrlArr)){
						//附件上传功能变更（JHSong）
						wsImageService.uploadAttachment(fileUrlArr, String.valueOf(response.getEntity().getId()), imageType, response.getEntity().getAccessCode());
					}
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception ex) {
				//新增业务操作异常记录
				businessLogServiceFacade.saveExceptionLog(user, "提交价格方案", gridJson, com.alibaba.fastjson.JSONObject.toJSONString(ex));
				
				logger.error("提交价格方案", ex);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
        //操作失败,重置防重复提交Token
        if(Const.FAIL == ar.getRes()){
        	ar.setObj(newToken);
        }
    	return ar;
    }
	
	public void saveProcessFile(String projectCode,String pid,String[] fileArr){
		if(null==fileArr || fileArr.length==0 || org.apache.commons.lang3.StringUtils.isBlank(pid) || org.apache.commons.lang3.StringUtils.isBlank(projectCode))return;
		User user = ShiroUtil.getCurrentUser();
		for(int ii=0; ii<fileArr.length; ii++){
			if(org.apache.commons.lang3.StringUtils.isNotEmpty(fileArr[ii])){
				try {
					ImageDto imageDto = new ImageDto();
					imageDto.setObjectId(Long.valueOf(pid));
					imageDto.setTitle("流程附件");
					imageDto.setContent("流程附件");
					imageDto.setSmallUrl(fileArr[ii]);
					imageDto.setImgType("6");
					imageDto.setMerchantId(user.getMerchantId());
					imageDto.setUserCode(user.getUserCode());
					imageDto.setAccessCode(projectCode);
					imageDto.setCreateUserId(user.getId());
					imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					imageServiceFacade.save(imageDto);
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:priceScheme:view"))){
        	try {
				Response<PriceScheme> response=priceSchemeServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//价格方案失效
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(PriceSchemeDto dto,String type){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:priceScheme:invalid"))){
        	try {
        		if(type.equals("1")){
        			dto.setInvalidId(ShiroUtil.getCurrentUser().getId());
        			dto.setInvalidTime(new Date());
        			priceSchemeDetailServiceFacade.updateRoomStatusByGroupId(dto.getId());
        		}
        		Response<Integer> response=priceSchemeServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:priceScheme:delete"))){
        	try {
        		Response<Integer> response=priceSchemeServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					//删除价格详情
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	
	
	//分页查询
	@RequestMapping(value="list")
	@ResponseBody
    public Page<PriceSchemeDto>  list(PriceSchemeDto dto,Integer page,Integer limit,String exTime,String inTime,String prefix, String prefixId){
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"marketing:priceScheme:list")){
        	try {
        		SimpleDateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        		if(!StringUtils.isEmpty(exTime)){
        			dto.setExecutionDate(df.parse(exTime+" 00:00:00"));
        		}
        		if(!StringUtils.isEmpty(inTime)){
        			dto.setInvalidTime(df.parse(inTime+" 23:59:59"));
        		}
        		dto.setDelFlag("0");
        		//Page<PriceScheme> response=priceSchemeServiceFacade.findPageByDto(dto, PageUtil.begin(page, limit),limit);
        		User user = ShiroUtil.getCurrentUser();
        		dto.setPermissionUserId(user.getId());
        		
        		//项目数据权限资源缓存
        		String resourcesCode = dto.getResourcesCode();
        		if(StringUtils.isEmpty(resourcesCode)){
        			resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
        			dto.setResourcesCode(resourcesCode);
        		}
        		ShiroUtil.setDataPermissionResources(dto.getResourcesName(), resourcesCode);
        		dto.setMerchantId(user.getMerchantId());
        		dto.setOrders(" t.execution_date desc");
        		Page<PriceSchemeDto> response=priceSchemeService.getPriceSchemeList(dto, PageUtil.begin(page, limit), limit);
                if(response.getSuccess()){
                    if(null==response.getRows())response.setRows(new ArrayList<PriceSchemeDto>());
                	response.setPageNumber(limit);
                	return response;
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
			}
    	}
    	return new Page<PriceSchemeDto>();
    }
	/**
	* 方法描述 : 房产树
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： PriceSchemeController.java
	* 版本： v1.0
	* 创建时间： 2016年6月22日 下午6:36:18
	* @return List<TreeNode>
	 */
	@RequestMapping(value = "treeNodeList")
	public @ResponseBody List<TreeNode> treeNodeList(ProjectDto projectDto){
	    	User user = ShiroUtil.getCurrentUser();
	    	projectDto.setPermissionUserId(user.getId());
	    	//缓存角色-项目树
	    	//String cacheKey = String.format(EhcacheConstant.PROJECT_TREE_KEY, user.getRoleId());
	    	//Object resources = cacheUtils.get(EhcacheConstant.ACTIVE_SESSIONS_CACHE, cacheKey);
	    	/*if(resources==null){*/
        	    projectDto.setPermissionUserId(user.getId());
        		//价格方案数据权限资源缓存
        		String resourcesCode = projectDto.getResourcesCode();
        		if(StringUtils.isEmpty(resourcesCode)){
        			resourcesCode = ShiroUtil.getDataPermissionResources(projectDto.getResourcesName());
        			projectDto.setResourcesCode(resourcesCode);
        		}
        		ShiroUtil.setDataPermissionResources(projectDto.getResourcesName(), resourcesCode);
        		projectDto.setMerchantId(user.getMerchantId());
        		ResponseList<TreeNode> treeNode = projectTreeServiceFacade.treeNodeList(projectDto);  
        		//cacheUtils.put(EhcacheConstant.ACTIVE_SESSIONS_CACHE,cacheKey,treeNode.getEntity());
        	   return treeNode.getEntity();
	    /*	}else{
	    	    return (List<TreeNode>)resources;
	    	}*/
	    	
		//价格方案数据权限资源缓存
	}
	
	/**
	* 方法描述 : 当前选中新增节点下所有的车位和房间
	* 创建者：ThinkPad 
	* 项目名称： emm-website
	* 类名： PriceSchemeController.java
	* 版本： v1.0
	* 创建时间： 2016年6月24日 上午11:25:16
	* @param treeId
	* @return List<PriceSchemeView>
	 */
	@RequestMapping(value = "findRoomList")
	public @ResponseBody List<PriceSchemeView> findRoomList(String treeId,String id, String noTradeHouse){
		if(!StringUtils.isEmpty(treeId)){
			List<PriceSchemeView> returnList = new ArrayList<PriceSchemeView>();
			List<PriceSchemeView> psvList = priceSchemeServiceFacade.findRoomList(treeId,id).getEntity();
			if(null != psvList && psvList.size() > 0){
				// 非认筹、认购、签约房源
				if ("1".equals(noTradeHouse)) {
					for(PriceSchemeView psv: psvList){
						String roomStatus = psv.getRoomStatus();
						if(org.apache.commons.lang.StringUtils.isNotBlank(roomStatus)){
							if(RoomStatusEnum.RESERVE.getNo().equals(roomStatus)
									|| RoomStatusEnum.BUY.getNo().equals(roomStatus)
									|| RoomStatusEnum.SIGN.getNo().equals(roomStatus)){
								continue;
							}
						}
						returnList.add(psv);
					}
				}else{
					returnList = psvList;
				}
			}

			return returnList;
		}else{
			return new ArrayList<PriceSchemeView>();
		}
	}
	/**
	* 方法描述 : 跳转价格方案无效审批页
	*/
	@RequestMapping(value = "toInvalid")
	public String toInvalid(ModelMap map,String priceSchemeId){
		map.put("priceSchemeId", priceSchemeId);
		Response<PriceScheme> priceScheme=priceSchemeServiceFacade.findById(Long.valueOf(priceSchemeId));
		if(priceScheme.isSuccess() && null!=priceScheme.getEntity()){
			String priceSchemeStr = JSON.toJSONString(priceScheme.getEntity());
			com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSONObject.parseObject(priceSchemeStr);
			map.put("priceScheme", data.toJSONString());
		}else{
			map.put("priceScheme", new com.alibaba.fastjson.JSONObject().toJSONString());
		}
		return "/marketing/priceScheme/priceSchemeInvalid";
	}
	
	
	/**
	* 方法描述 : 提交价格方案无效审核
	*/
	@RequestMapping(value = "submitInvalid")
	public @ResponseBody AjaxRes submitInvalid(Long priceSchemeId, String remark,String fileUrlArr, String imageType) {
		AjaxRes ar = getAjaxRes();
		User user = ShiroUtil.getCurrentUser();
		try {
			Response<PriceScheme> priceSchemeResponse=priceSchemeServiceFacade.findById(Long.valueOf(priceSchemeId));
			if (!priceSchemeResponse.isSuccess() || null == priceSchemeResponse.getEntity()) {
				ar.setFailMsg(Const.SAVE_FAIL);
				return ar;
			}
			PriceScheme priceScheme=priceSchemeResponse.getEntity();
			String status=priceScheme.getStatus();
			if(!status.equals("10")){
				ar.setFailMsg("该价格方案为非生效状态，不可设置为无效状态！");
				return ar;
			}
			Long projectId=priceScheme.getProjectId();
            if(null==projectId){
                ar.setFailMsg("项目不存在!");
                return ar;
            }
    		//检查流程节点是否已设置人员
            String startProcessKey= activitiProcessService.getProcessKey(user.getMerchantId(),projectId,ProcessTypeEnums.PROCESS_KEY_2);
            if(StringUtils.isEmpty(startProcessKey)){
                ar.setFailMsg("未设置价格方案无效审批流程");
                return ar;
            }
    		boolean isSeting=activitiProcessService.checkNodeUser(user.getMerchantId(),projectId,startProcessKey);
    		if(!isSeting){
    			ar.setFailMsg("价格方案无效审批流程节点人员未设置");
    			return ar;
    		}
    		
    		BusinessAbnormaDto businessAbnormaDto=new BusinessAbnormaDto();
    		businessAbnormaDto.setMerchantId(user.getMerchantId());
    		businessAbnormaDto.setBusinessId(priceScheme.getId());
    		businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_10.getNo());
    		ResponseList<BusinessAbnorma> baList=businessAbnormaServiceFacade.findByDto(businessAbnormaDto);
    		if(baList.isSuccess() && null!=baList.getEntity()){
    			for(BusinessAbnorma ba : baList.getEntity()){
    				String auditStatus=ba.getAuditStatus();
    				if(auditStatus.equals(AuditStatusEnum.TOSUBMIT.getNo()) || auditStatus.equals(AuditStatusEnum.AUDIT.getNo()) ){
    					ar.setFailMsg("该条记录正在失效审批中，请勿重复提交");
            			return ar;
    				}
    			}
    		}
			
			BusinessAbnormaDto dto = new BusinessAbnormaDto();
			dto.setBusinessId(priceScheme.getId());
			dto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_10.getNo());
			dto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
			dto.setRemark(remark);
			dto.setMerchantId(user.getMerchantId());
			dto.setCreateUserId(user.getId());
			dto.setDelFlag("0");
			dto.setUpdateUserId(user.getId());
			dto.setUpdateTime(new Date());
			dto.setUserCode(user.getUserCode());
			dto.setAccessCode(priceScheme.getAccessCode());
			Response<BusinessAbnormaDto> response = businessAbnormaServiceFacade.save(dto);
			if (response.isSuccess()) {
				identityService.setAuthenticatedUserId(user.getUserAccount());
				String pid=activitiProcessService.startProcessInstance(user.getMerchantId(),projectId,startProcessKey,response.getEntity().getId().toString(), null);
				// 更新审批状态
				BusinessAbnormaDto updateDto = new BusinessAbnormaDto();
				updateDto.setId(response.getEntity().getId());
				updateDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
				updateDto.setProcInstId(pid);
				updateDto.setCheckDate(new Date());
				businessAbnormaServiceFacade.updateByPrimaryKey(updateDto, true);
				//保存流程附件
				if(org.apache.commons.lang3.StringUtils.isNotBlank(fileUrlArr)){
                 	wsImageService.uploadAttachment(fileUrlArr, String.valueOf(response.getEntity().getId()), imageType, response.getEntity().getAccessCode());
                }
				
				ar.setSucceed("");
			} else {
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		} catch (Exception ex) {
			//新增业务操作异常记录
			businessLogServiceFacade.saveExceptionLog(user, "提交价格无效方案", String.valueOf(priceSchemeId), com.alibaba.fastjson.JSONObject.toJSONString(ex));
			
			logger.error("提交价格无效方案", ex);
			ar.setFailMsg(Const.SAVE_FAIL);
		}
		return ar;
	}

	/**
	* 方法描述 : 跳转价格方案无效审批详情页
	*/
	@RequestMapping(value = "toInvalidView")
	public String toInvalidView(ModelMap map,String id,String processFlag){
		Response<BusinessAbnorma> businessAbnormaResponse=businessAbnormaServiceFacade.findById(Long.valueOf(id));
		Response<PriceScheme> priceScheme=priceSchemeServiceFacade.findById(Long.valueOf(businessAbnormaResponse.getEntity().getBusinessId()));
		if(priceScheme.isSuccess() && null!=priceScheme.getEntity()){
			String priceSchemeStr = JSON.toJSONString(priceScheme.getEntity());
			com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSONObject.parseObject(priceSchemeStr);
			data.put("invalidRemark", businessAbnormaResponse.getEntity().getRemark());
			if(null!=priceScheme.getEntity().getExecutionDate())
			data.put("executionDate", DateUtils.DateToString(priceScheme.getEntity().getExecutionDate(), DateStyle.YYYY_MM_DD));
			map.put("priceScheme", data.toJSONString());
		}else{
			map.put("priceScheme", new com.alibaba.fastjson.JSONObject().toJSONString());
		}
		map.put("businessAbnormaId", businessAbnormaResponse.getEntity().getId());
		map.put("priceSchemeId", businessAbnormaResponse.getEntity().getBusinessId());
		map.put("auditStatus", businessAbnormaResponse.getEntity().getAuditStatus());
		map.put("processFlag", processFlag);
		map.put("procInstId", businessAbnormaResponse.getEntity().getProcInstId());
		return "/marketing/priceScheme/priceSchemeInvalidView";
	}
}
